72. Edit Distance

#Algorithm #Algorithm_Levenshtein #Algorithm_DP

72. Edit Distance

1. 문제

1-1. 원문

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

Constraints:

1-2. 내용 번역

주어진 두 문자열 word1와 word2가 있을 때, word1을 word2로 만들기 위해 수행하는 operation의 최소 횟수를 구하여라.
operation의 종류는 문자 삽입, 삭제, 대체 3종류가 있다.


2. 문제 이해

2-1. 내용 이해

음... Example들을 보면 이해가 되었다.

2-2. 접근법 생각

Levenshtein 문제이다.

2-3. 적용한 풀이

Levenshtein


3. 구현

class Solution {
    fun minDistance(word1: String, word2: String): Int {
        val rowSize = word2.length + 1
        val colSize = word1.length + 1
        val memo: Array<IntArray> = Array(rowSize){IntArray(colSize)}

        for(word2Idx in 0 until rowSize) {
            memo[word2Idx][0] = word2Idx
        }

        for(word1Idx in 0 until colSize) {
            memo[0][word1Idx] = word1Idx
        }

        for(word2Idx in 1 until rowSize) {
            for(word1Idx in 1 until colSize) {
                memo[word2Idx][word1Idx] = if (word1.get(word1Idx-1) == word2.get(word2Idx-1)) {
                    memo[word2Idx-1][word1Idx-1]
                } else {
                    val insert = memo[word2Idx-1][word1Idx] + 1
                    val delete = memo[word2Idx][word1Idx-1] + 1
                    val replace = memo[word2Idx-1][word1Idx-1] + 1
                    minOf(insert, delete, replace)
                }
            }
        }

        return memo[rowSize-1][colSize-1]
    }
}